// JavaScript Document

var sites = {
	
    selected: null,
    
    ajax_page: 'ajax_pages/sites.php',
	
    /**
	 * Iniitializes the site script object and loads the necessary editors for the various
	 * textareas
	 */
    init: function(params) {
    

        // bind the activation links
        $p(".activator").bind('click', function(){
            var status = $p(this).attr("data-status");
            var siteid = $p(this).attr("data-id");
            var activator = this;
            
            sites.setActive(siteid, status, activator);
        });

        $p.all("#site_actions_link", function(el, i) {
			
            var siteid = el.getAttribute("data-id");
			
            ui.menu( el, { 
                items: [{
                    id: 'sad-' + siteid,
                    name: "Activate",
                    title: "Set Selected Sites As Active",
                    action: function() {
                        sites.setSelectedActive( true );
                    }
                },{
                    id: 'sad-' + siteid,
                    name: "Deactivate",
                    title: "Set Selected Sites As Inactive",
                    action: function() {
                        sites.setSelectedActive(false);
                    }
                },{
                    id: 'del-' + siteid,
                    name: "Delete",
                    title: "Delete Selected",
                    action: function() {
                        sites.deleteSelectedSites();
                    }
                },{
                    id: 'clear-' + siteid,
                    name: 'Clear Cache',
                    title: 'Clear Site Cache',
                    action: function() {
                        sites.clearCache();
                    }
                }] 
            });
        });

        
        if( params.siteid != -1 ) {
            sites.loadSelectedStyle();
        }
    },

    /**
     * Sets the sites selected by the user
     */
    setSelectedSites: function(selectedSites) {
        sites.selected = selectedSites;
    },

    /**
     * Returns the sites selected by the user
     */
    getSelectedSites: function() {

        var checkBoxes = $p.all("#sites_form input[type=checkbox]");
        var selected = new Array();
		
        for(var i = 0, j = 0; i < checkBoxes.length; i++) {
            if( checkBoxes[i].checked ) {
                selected[j++] = checkBoxes[i].value;
            }
        }
		
        return sites.selected = selected;
    },

    /**
     * Filters the Sites List to show only the sites which contain the specified
     * word in the term
     */
    filterSiteList: function(word) {
        if( word == "" ) {
            sites.showAllBoxes();
            return;
        }
		
		$p.all("#site_list div.site_box", function(el){
			
			if( $p(el).text().toLowerCase().indexOf(word.toLowerCase()) == -1 ) {
				$p(el).css('display','none');
			} else {
				$p(el).css('display','block');	
			}
		});
    },
	
    /**
     * Resets the Site Lists so all sites are shown
     */
    showAllBoxes: function() {
        var siteList = document.getElementById("site_list");
		
        var boxes = siteList.getElementsByTagName("div");
        for(var i = 0; i < boxes.length; i++) {
            var div = boxes.item(i);
            if( div.className == "site_box" ) {
                div.style.display = 'block';
            }
        }
    },

    /**
     * Deletes the specified site from the system by forwarding an AJAX call
     * to the server to initiate the process. The callback hides and removes
     * the site display box from the UI
     */
    deleteSite: function(id) {
        if( confirm('Do you want to delete the specified site and all related data?') ) {
			
            var query = "action=delete&items=1&item1=" + id;
            $p.post( sites.ajax_page, query, function() {
                //sites.postDeleteProcessing([id])
                
                var siteBox = document.getElementById("sitebox" + id);
				
				if( siteBox == null ) return;
				
				// hide each of the deleted sites
				$p(siteBox).hide( function() {
					// remove the siteBox from the display
					siteBox.parentNode.removeChild( siteBox );
				});
            });
        }
		
        return false;
    },

    /**
     * Deletes the selected sites from the system by forwarding a call to the
     * server via AJAX. The callback hides and removes all the selected sites
     * from the UI display
     */
    deleteSelectedSites: function() {

        var checkBoxes = $p.all("#sites_form input[type=checkbox]");
        var selected = new Array();
		
        for(var i = 0; i < checkBoxes.length; i++) {
            if( checkBoxes[i].checked ) {
                selected[i] = checkBoxes[i].value;
            }
        }
		
        if( selected.length == 0 ) {
            alert("Please Select Site(s) To Delete");
            return;
        }
		
        if( !confirm("Delete Selected Sites? Note: Process Cannot Be Undone!") ) {
            return;
        }
		
		
        var postStr = "&action=delete&items=" + checkBoxes.length;
        var query = $p("#sites_form").serialize() + postStr;
        $p.post( sites.ajax_page, query, function() {
			
			for(var i = 0; i < selected.length; i++) {
				
				// hide each of the deleted sites
				$p("#sitebox" + selected[i]).hide( function() {
					// remove the siteBox from the display
					$p(this).remove();
				});
			}
			
			// once processing is done, we can hide the indicator
			sites.hideProgressIndicator();
		});
    },

    /**
     * Sets the default site for the system by forwarding the required
     * parameters via AJAX to the server. The callback action updates the
     * UI and indicates the new selected site
     */
    setDefault: function(id) {
        if( confirm('Set Selected Site As Default Site?') ) {
  		
			var selected = id;
			
            var query = "action=set_default&id=" + id;
            $p.post( sites.ajax_page, query, function() {
				$p(".site_box").removeClass("default_site");
				$p("#sitebox" + selected).addClass("default_site");	
			});
        }
		
        // always return false do the link is not processed
        return false;
    },

    setActive: function(id, status, activator) {
        var text = status == '0' ? "Active" : "Inactive"
        if( confirm('Set Selected Site As ' + text + '?') ) {

            var query = "action=set_active&ids=" + id + "&state=" + (status == '0' ? 'active' : 'inactive');
            $p.post( sites.ajax_page, query, function(data) {
                $p("#ajax_content").html(data);
                $p(activator).attr("data-status", status == '0' ? '1' : '0');
                $p(activator).html( status == '0' ? 'De-Activate' : 'Activate' );

                if( status == '0' ) {
                    $p("#sitebox" + id).removeClass("inactive");
                } else {
                    $p("#sitebox" + id).addClass("inactive");
                }
                
            });
        }

        // always return false do the link is not processed
        return false;
    },
	
    /**
	 * @param status boolean representing true or false
	 */
    setSelectedActive: function(status) {
        var ids = sites.getSelectedSites();
		
        if( ids == null || ids.length == 0 ) {
            alert("Please Select Sites To Change Active Status For");
            return false;	
        }
		
        var text = status ? "Active" : "Inactive"
        if( confirm('Set Selected Sites As ' + text + '?') ) {

            var query = "action=set_active&ids=" + ids + "&state=" + (status ? 'active' : 'inactive');

            $p.post( sites.ajax_page, query, function(data) {
				$p("#ajax_content").html(data);
                
                for(i = 0; i < ids.length; i++) {
                    var activator = "#sitebox" + ids[i] + " .activator";
                    $p(activator).attr("data-status", status ? '1' : '0');
                    $p(activator).html( status ? 'De-Activate' : 'Activate' );
					
                    if( status ) {
                        $p("#sitebox" + ids[i]).removeClass("inactive");
                    } else {
                        $p("#sitebox" + ids[i]).addClass("inactive");
                    }
                }
            });
        }

        // always return false do the link is not processed
        return false;
    },
    
    clearCache: function() {
        var ids = sites.getSelectedSites();
		
        if( ids == null || ids.length == 0 ) {
            alert("Please Select Sites For Which You Want Cache Cleared");
            return;	
        }
        
        if( confirm('The Site Cache Will Be Cleared For The Selected Sites. Do you want to continue?') ) {

            var query = "action=clear_cache&ids=" + ids;

            $p.post( sites.ajax_page, query, function() {
                alert("Site Cache Cleared. Click OK To Continue");
            });
        }
    },

    /**
     * Indicates that a specific AJAX process in progress by updating the UI
     * to show a progress indicator
     */
    showProgressIndicator: function() {
        document.getElementById("ajax_progress").style.display = "inline-block";
    },

    /**
     * Hides the progress indicator for the AJAX process
     */
    hideProgressIndicator: function() {
        document.getElementById("ajax_progress").style.display = "none";
    },
	
    /**
	 * Load the list of CSS Style for the selected theme
	 */
    loadCSSListForTheme: function(themeid, cssid) {
        var query = "?themeid=" + themeid + "&cssid=" + cssid;
        $p.get("ajax_pages/theme_css_list_loader.php",query,function(data) {
            $p("#theme_list").html(data);
        });
    },
	
    /**
	 * Load the selected style information
	 */
    loadSelectedStyle: function() {
        var themeid = document.getElementById("SiteThemeID").value;
        var cssid = document.getElementById("TempCSSID");
		
        if( cssid != null ) {
            cssid = cssid.value;
            sites.loadCSSListForTheme(themeid,cssid);	
        } else {
            sites.loadCSSListForTheme(themeid);
        }
    }
};